package mywebapps.security.jsf;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.model.SelectItem;

import mywebapps.security.dao.RoleDao;
import mywebapps.security.dao.UserRoleDao;
import mywebapps.security.model.Role;

public class EditUserRolesAction
{
    private RoleDao roleDao;
    private UserRoleDao userRoleDao;
    private Integer userId;
    private List<String> chosenRoles;
    private List<SelectItem> allRoles;

    @PostConstruct
    public void init()
    {
        allRoles = new ArrayList<SelectItem>();
        chosenRoles = new ArrayList<String>();
        
        if (userId != null) {
            List<Role> roles = roleDao.getAllRoles();
            for (Role role : roles) {
                SelectItem roleItem = new SelectItem(String.valueOf(role.getRoleId()), role.getRoleName());
                allRoles.add(roleItem);
            }
            
            Role[] userRoles = userRoleDao.getUserRoles(userId);
            for (Role role : userRoles) {
                chosenRoles.add(String.valueOf(role.getRoleId()));
            }
        }
    }
    
    public String save()
    {
        userRoleDao.updateUserRoles(userId, convertStringToIntList(chosenRoles));
        return "gotoEditUser";
    }
    
    private List<Integer> convertStringToIntList(List<String> oldList)
    {
        List<Integer> newList = new ArrayList<Integer>();
        for(String value : oldList) {
            newList.add(Integer.valueOf(value));
        }
        
        return newList;
    }
    
    public void setRoleDao(RoleDao roleDao)
    {
        this.roleDao = roleDao;
    }

    public void setUserRoleDao(UserRoleDao userRoleDao)
    {
        this.userRoleDao = userRoleDao;
    }

    public Integer getUserId()
    {
        return userId;
    }

    public void setUserId(Integer userId)
    {
        this.userId = userId;
    }

    public List<String> getChosenRoles()
    {
        return chosenRoles;
    }

    public void setChosenRoles(List<String> chosenRoles)
    {
        this.chosenRoles = chosenRoles;
    }

    public List<SelectItem> getAllRoles()
    {
        return allRoles;
    }

    public void setAllRoles(List<SelectItem> allRoles)
    {
        this.allRoles = allRoles;
    }
}
